﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace TestCenterUI
{
	public partial class ComboBoxForm : Form
	{
		ComboBox cb;
		Form form;
		List<object> items;

		public ComboBoxForm()
		{
			InitializeComponent();
		}

		public int FormWidth
		{
			get
			{ return listBox1.Width; }
			set
			{
				listBox1.Width = value;
				this.Width = listBox1.Width;
			}
		}

		public void Show(ComboBox cb, Form form)
		{
			this.cb = cb;
			this.form = form;

			items = new List<object>();
			foreach (var item in cb.Items)
				items.Add(item);

			listBox1.Items.Clear();
			foreach (var item in cb.Items) 
				listBox1.Items.Add(item); 

			SetLocation();
			Show();

			listBox1.Select();
			cb.Focus();

			Deactivate += ComboBoxForm_Deactivate;
			cb.Leave += Cb_Leave;
			form.Move += Form_Move;
			cb.KeyDown += Cb_KeyDown;
		}

		private void Cb_KeyDown(object sender, KeyEventArgs e)
		{
			if (form.Visible == false)
				form.Show();
			listBox1.Items.Clear();
			foreach (var item in items.Where(item => item.ToString().Contains(cb.Text)))
			{
				listBox1.Items.Add(item);
			}
		}

		private void SetLocation()
		{
			if (cb != null && form != null)
			{
				Location = form.PointToScreen(cb.Location);
				Top += cb.Height + 2;
				FormWidth = cb.Width;
			}
		}

		private void Form_Move(object sender, EventArgs e)
		{
			Hide();
		}

		private void Cb_Leave(object sender, EventArgs e)
		{
			Hide();
		}

		private void ComboBoxForm_Deactivate(object sender, EventArgs e)
		{
			if (!cb.Focused)
				Hide();
		}


		private void ComboBoxForm_Load(object sender, EventArgs e)
		{
			this.Size = listBox1.Size;
			listBox1.KeyDown += (s, e1) =>
			{
				if (e1.KeyCode == Keys.Enter)
					Hide();
			};
		}

		private void ComboBoxForm_Leave(object sender, EventArgs e)
		{

		}

		private void ComboBoxForm_FormClosing(object sender, FormClosingEventArgs e)
		{
			Deactivate -= ComboBoxForm_Deactivate;
			cb.Leave -= Cb_Leave;
			form.Move -= Form_Move;
			cb = null;
			form = null;
		}
	}
}
